<template>
	<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
		<el-form-item prop="user">
			<el-input v-model="form.user" prefix-icon="el-icon-user" clearable :placeholder="$t('login.userPlaceholder')">
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
		</el-form-item>
			<el-form-item prop="code" v-if="verifyCode=='1'">
				<el-input v-model="form.code" clearable :placeholder="$t('login.verifyCode')" style="width: 60%" maxlength="4"></el-input>
				<el-image :src="verifyCodeUrl" style="width: 40%;height: 40px;cursor: pointer;" @click="changeVerifyCode"></el-image>
			</el-form-item>
		<el-form-item style="margin-bottom: 10px;" v-if="findPass=='1'||remUserPass=='1'">
			<el-col :span="12">
				<el-checkbox v-model="form.autologin" :checked="form.autologin" style="color:white;" v-if="remUserPass=='1'">
					<span :style="`color:`+appColor">
						{{$t('login.rememberMe')}}
					</span>
					</el-checkbox>
			</el-col>
			<el-col :span="12" class="login-forgot">
				<router-link to="/forget_password" v-if="findPass=='1'" :style="`font-weight:500;color:`+appColor">{{ $t('login.forgetPassword') }}？</router-link>
			</el-col>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :style="`width: 100%;background-color:`+appColor+`;border-color:`+appColor" :loading="islogin" round @click="login">{{ $t('login.signIn') }}</el-button>
		</el-form-item>
	</el-form>
</template>
<script>
import {ParamEncrypt} from "@/utils/util"
import resetPassword from '../resetPassword'
import CryptoJS from 'crypto-js'
import config from "@/config";
export default {
	props:{
		verifyCode:	{type:String},
		remUserPass:{type:String},
		findPass:{type:String},
		appColor:{type:String},
	},
	components: {
		resetPassword,
	},
	data() {
		return {
			user: "",
			password: "",
			verifyCodeUrl:config.API_URL+'/get/file/getVerifyCodeImage',
			form: {
				user: "",
				password: "",
				code:'',
				autologin: false
			},
			rules: {
				user: [
					{required: true, message: this.$t('login.userError'), trigger: 'blur'}
				],
				password: [
					{required: false, message: this.$t('login.PWError'), trigger: 'blur'}
				],
			},
			islogin: false,
		}
	},
	watch: {
		verifyCode(val) {
			if(val=='1')
			{
				this.rules.code=[
					{required: true, message: this.$t('login.VCError'), trigger: 'blur'}
				]
			}
		}
	},
	mounted() {
		const { username, password } = this.$route.query;
		console.log("Username:", username);
		console.log("password:", password);
		// 参数存在性检查 + 逻辑分层
		if (username && password) {
			// 仅在参数齐全时执行登录逻辑
			this.form.user = username;
			this.form.password = password;
			this.login();
		}
		// const { username, password } = this.$route.query;
		// if (username) this.username = username;
		// if (password) this.password = password;
		// if (!username || !password) {
		// 	console.log("Username:", username); // 任意一个为空时打印 username
		// } else {
		// 	this.form.user = username;
		// 	this.form.password = password;
		// 	this.login();
		// 	console.log("Password:", password); // 都不为空时打印 password
		// }
	    // 监听键盘事件，以支持快捷键登录功能
	    document.onkeydown = (e) => {
	        if (e.defaultPrevented) {
	            return;
	        }
	        const body = document.getElementsByTagName('body')[0];
	        // match(xxxx应填写文件在浏览器中的地址，不需要包括https、http或者www)，这里是为了防止其他页面触发
	        if (e.keyCode === 13 && e.target.baseURI.match("/login") && e.target === body) {
	            this.login(); //需要调用的方法
	        }
	    };
	    // 自动登录逻辑：从cookie中读取自动登录设置
	    this.form.autologin = this.$TOOL.cookie.get("AUTO_LOGIN")=='true'?true:false;
	    // 如果用户选择了自动登录且记住密码，则进行相应的处理
	    if(this.form.autologin&&this.remUserPass=='1')
	    {
	        // 清除可能存在的TOKEN，以确保安全
	        this.$TOOL.cookie.remove("TOKEN");
	        // 从cookie中读取用户名
	        this.form.user = this.$TOOL.cookie.get("ACCOUNT_ID");
	        // 如果密码存在，则进行解密并填充到表单中
	        if(this.$TOOL.cookie.get("PASS_WORD")!='')
	        {
	            this.form.password = this.$TOOL.cookie.get("PASS_WORD");
	        }
	    }
	},
	methods: {
		changeVerifyCode()
		{
			this.verifyCodeUrl = config.API_URL+'/get/file/getVerifyCodeImage?_='+new Date();
		},
		async login() {
			var validate = await this.$refs.loginForm.validate().catch(() => {
			})
			if (!validate) {
				return false
			}
			this.islogin = true
			var data = {
				accountId: this.form.user, // 删除: ParamEncrypt(this.form.user),
				passWord: this.form.password, // 删除: ParamEncrypt(this.form.password),
				code:this.form.code
			}
			//获取token
			var user = await this.$API.auth.token.post(data);
			console.log('user', user);
			if (user.code == 200) {
				console.log('this.form.autologin', this.form.autologin);
				if(this.form.autologin)
				{
					this.$TOOL.cookie.set("ACCOUNT_ID", this.form.user, {
						expires: 24 * 60 * 60
					})
					this.$TOOL.cookie.set("PASS_WORD", this.form.password, { // 删除: CryptoJS.AES.encrypt(this.form.password, this.form.user),
						expires: 24 * 60 * 60
					})
					this.$TOOL.cookie.set("AUTO_LOGIN", this.form.autologin, {
						expires: 24 * 60 * 60
					})
				}else {
					this.$TOOL.cookie.remove("ACCOUNT_ID");
					this.$TOOL.cookie.remove("PASS_WORD");
					this.$TOOL.cookie.remove("AUTO_LOGIN");
				}
				this.$TOOL.cookie.set("TOKEN", user.data.token, {
					expires:24 * 60 * 60
				})
				this.$TOOL.data.set("USER_INFO", user.data.userInfo)
				this.$TOOL.data.set('APP_LANG', user.data.userInfo.language);
				this.$TOOL.data.set('APP_COLOR', user.data.userInfo.theme);
				this.$TOOL.data.set("MSG_TIME",user.data.msgtime);
				this.$TOOL.data.set("WATER_MARK",user.data.waterMark);
				this.$TOOL.data.set("WATER_MARK_CONTENT",user.data.waterMarkContent);
				this.$TOOL.data.set("WATER_MARK_SUBTEXT",user.data.waterMarkSubtext);

				this.islogin = false
			}else if(user.code==-1){
				this.$alert(user.data, "提示", {type: 'error'});
				this.islogin = false;
				return false;
			}else if (user.code == 300) {
				this.$router.replace({
					path: '/system/info'
				})
				return;
			} else if (user.code == 400) {
				this.$router.replace({
					path: '/resetPassword'
				})
				return;
			} else {
				this.islogin = false
				this.$message.warning(user.message)
				return false
			}
			//获取菜单
			console.log('55555555555')
			var menu = await this.$API.system.menu.myMenus.get()
			if (menu.code == 200) {
				if (menu.data.menu.length == 0) {
					this.islogin = false
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				this.$TOOL.data.set("MENU", menu.data.menu)
				this.$TOOL.data.set("PERMISSIONS", [
					"list.add",
					"list.edit",
					"list.delete",
					"user.add",
					"user.edit",
					"user.delete"
				])

				/*if(menu.data.menu.length==0){
					this.islogin = false
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				this.$TOOL.data.set("MENU", menu.data.menu)
				this.$TOOL.data.set("PERMISSIONS", menu.data.permissions)*/
			} else {
				this.islogin = false
				this.$message.warning(menu.message)
				return false
			}
			this.$router.replace({
				path: '/'
			})
			this.$message.success("Login Success 登录成功")
			this.islogin = false
		},
	}
}
</script>

<style>
</style>

